import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
import store from "@/store";
Vue.use(VueRouter);
const router = new VueRouter({
  mode: "history",
  routes,
  //滚动行为 vue2中 vue-router必须3.1.0版本以上才生效
  /*scrollBehavior() {
    return {
      left: 0,
      top: 0,
    };
  },*/
  scrollBehavior(to, from, savedPosition) {
    // 如果有保存的位置，则返回它
    if (savedPosition) {
      return savedPosition;
    }
    // 否则滚动到顶部
    return { y: 0 };
  },
});
// 全局守卫：前置守卫
router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token;
  let userName = store.state.user.userInfo.name;
  if (token) {
    if (to.path === "/login") {
      next("/home");
    } else {
      if (userName) {
        next();
      } else {
        try {
          await store.dispatch("getUserInfo");
          next();
        } catch (error) {
          await store.dispatch("userLogOut");
          next("/login");
        }
      }
    }
  } else {
    //未登录不能去trade pay center
    console.log(to.path);
    //TODO 去往center页面的问题
    if (to.path == "/trade" || to.path == "/pay" || to.path == "/center") {
      next(`/login?redirect=${to.path}`);
    } else {
      next();
    }
  }
});
export default router;
